<template>
  <el-dialog
      v-model="dialogVisible"
      title="修改分类"
      width="600px"
      :before-close="handleCloseDialog"
  >
    <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
        class="category-edit-form"
    >
      <el-form-item label="父分类" prop="parentId">
        <el-tree-select
            v-model="editForm.parentId"
            :data="filteredCategoryTreeData"
            :render-after-expand="false"
            :check-strictly="true"
            placeholder="请选择父分类"
            class="category-edit-form-tree-select"
            :props="{
            value: 'id',
            label: 'name',
            children: 'children'
          }"
        />
      </el-form-item>

      <el-form-item label="分类名称" prop="name">
        <el-input
            v-model="editForm.name"
            placeholder="请输入分类名称"
            class="category-edit-form-input"
        />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input
            v-model.number="editForm.sort"
            placeholder="请输入排序值"
            class="category-edit-form-input"
            type="number"
            :min="0"
            :max="9999"
            @input="handleSortInput"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="category-edit-dialog-footer">
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, watch, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {getCategoriesTree, updateCategory} from "../../../api/categoryApi.js";

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  categoryData: {
    type: Object,
    default: () => ({})
  }
})

// 定义emits
const emits = defineEmits(['update:visible', 'success'])

// 对话框显示状态
const dialogVisible = ref(false)

// 表单引用
const editFormRef = ref()

// 分类树数据
const categoryTreeData = ref([])

// 修改表单数据
const editForm = reactive({
  id: null,
  parentId: null,
  name: '',
  sort: 0
})

// 表单验证规则
const editFormRules = reactive({
  parentId: [
    {required: true, message: '请选择父分类', trigger: 'change'}
  ],
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur'}
  ]
})

// 过滤后的分类树数据（排除当前分类及其子分类）
const filteredCategoryTreeData = computed(() => {
  if (!categoryTreeData.value.length || !editForm.id) {
    return categoryTreeData.value
  }

  // 递归函数：过滤掉当前分类及其所有子分类
  const filterTree = (nodes) => {
    return nodes.filter(node => {
      if (node.id === editForm.id) {
        return false
      }
      if (node.children && node.children.length > 0) {
        node.children = filterTree(node.children)
      }
      return true
    }).map(node => ({ ...node }))
  }

  return filterTree(categoryTreeData.value)
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    loadCategoryTree()
    initFormData()
  }
})

// 监听dialogVisible变化，同步到父组件
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    emits('update:visible', false)
  }
})

// 初始化表单数据
const initFormData = () => {
  if (props.categoryData) {
    editForm.id = props.categoryData.id
    editForm.parentId = props.categoryData.parentId
    editForm.name = props.categoryData.name
    editForm.sort = props.categoryData.sort || 0
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  editForm.id = null
  editForm.parentId = null
  editForm.name = ''
  editForm.sort = 0
}

// 提交表单
const handleSubmit = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    await updateCategory(editForm)
    // 通知父组件操作成功
    emits('success', editForm)
    handleCloseDialog()
  } catch (error) {
    console.error('表单验证失败或修改失败:', error)
  }
}

// 加载分类树数据
const loadCategoryTree = async () => {
  try {
    const res = await getCategoriesTree()
    // 确保数据是数组格式，如果后端返回单个对象，需要包装为数组
    if (res && typeof res === 'object' && !Array.isArray(res)) {
      categoryTreeData.value = [res]
    } else if (Array.isArray(res)) {
      categoryTreeData.value = res
    } else {
      categoryTreeData.value = []
    }
  } catch (error) {
    console.error('加载分类树失败:', error)
    ElMessage.error('加载分类数据失败')
  }
}

// 处理排序输入
const handleSortInput = (value) => {
  // 只允许输入整数
  const intValue = parseInt(value, 10)
  if (!isNaN(intValue)) {
    editForm.sort = intValue
  } else {
    editForm.sort = 0
  }
}
</script>

<style scoped lang="scss">
.category-edit {
  &-form {
    padding: 16px 0;

    &-tree-select {
      width: 100%;
    }

    &-input {
      width: 100%;
    }

    &-input-number {
      width: 100%;
    }
  }

  &-dialog {
    &-footer {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
    }
  }
}
</style>
